#!/bin/bash
#
# alg2docker 0.3
#
# Convert an Algernon application (.alg or .zip) to a Dockerfile
#

if [[ $1 == "" || $1 == "-h" || $1 == "--help" ]]; then
  echo 'alg2docker 0.4.0'
  echo
  echo 'Convert an Algernon application (.alg or .zip) to a Dockerfile'
  echo
  echo 'Usage:'
  echo '    alg2docker [-f] ALGFILE [DOCKERFILE] [NAME] [EMAIL]'
  echo
  echo 'Example:'
  echo "    alg2docker hello.alg Dockerfile '$name' '$email'"
  echo
  exit 1
fi

filename=hello.alg
newfile=Dockerfile
name="$(whoami)"
email="$EMAIL"
force="false"

if [[ $1 == "-f" ]]; then
  force="true"
  shift
fi

if [[ $1 != "" ]]; then filename="$1"; fi
if [[ $2 != "" ]]; then newfile="$2"; fi
if [[ $3 != "" ]]; then name="$3"; fi
if [[ $4 != "" ]]; then email="$4"; fi

basefilename=$(basename "$filename")

basedockerfilename=$(basename "$newfile")
if [[ "$basedockerfilename" != Dockerfile ]]; then
  echo "ERROR: expected Dockerfile, got $basedockerfilename"
  exit 1
fi


if [[ -e $newfile && $force == "false" ]]; then
  echo "ERROR: file already exists: $newfile"
  echo "Use -f as the first argument to overwrite."
  exit 1
fi

echo "Using this Algernon application: $filename"
echo "Creating this Dockerfile: $newfile"

cat <<EOF > "$newfile"
FROM golang as builder
LABEL MAINTAINER="%EMAIL%"

# Install Algernon
RUN CGO_ENABLED=0 go install -trimpath -ldflags "-s" -a -v github.com/xyproto/algernon@latest

# Copy in in the .alg file
COPY %FILENAME% %FILENAME%

# Start a new Dockerfile based on Alpine
FROM alpine
LABEL MAINTAINER="%EMAIL%"
RUN apk add --no-cache ca-certificates

# Mount the configuration, cert and keys
#VOLUME /etc/algernon

# Copy in the .alg file
COPY %FILENAME% /srv/algernon/%BASEFILENAME%

# Copy in the Algernon executable from the builder docker
COPY --from=builder /go/bin/algernon /usr/bin/algernon

# Expose port 80 (HTTP) and 443 (HTTPS)
EXPOSE 80 443

# Serve over HTTPS using the custom cert and key
CMD ["/usr/bin/algernon", "-c", "--cachesize", "67108864", "--cert", "/etc/algernon/cert.pem", "--key", "/etc/algernon/key.pem", "-n", "--prod", "--server", "/srv/algernon/%BASEFILENAME%"]

EOF

# Use sed differently on macOS and on Linux
# TODO: Add a check for *BSD
if [[ "$OSTYPE" == "darwin"* ]]; then
    # macOS
    sed -i '' "s|%NAME%|$name|g" "$newfile"
    sed -i '' "s|%EMAIL%|$email|g" "$newfile"
    sed -i '' "s|%FILENAME%|$filename|g" "$newfile"
    sed -i '' "s|%BASEFILENAME%|$basefilename|g" "$newfile"
else
    # Linux
    sed "s|%NAME%|$name|g" -i "$newfile"
    sed "s|%EMAIL%|$email|g" -i "$newfile"
    sed "s|%FILENAME%|$filename|g" -i "$newfile"
    sed "s|%BASEFILENAME%|$basefilename|g" -i "$newfile"
fi
